package connector;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

/**
 * Klasa reprezentuje połączenie pomiędzy klientem a serwerem.
 * 
 * @author Maciej Graszek
 * @author Pawel Rychly
 * 
 */
public class Connector implements Runnable {

	private Socket clientSocket = null;
	private ObjectInputStream in = null;
	private ObjectOutputStream out = null;
	private String adres = "localhost";
	private boolean isRunning = false;

	private int portNumber = 3001;
	private InetAddress adr;

	public Connector() throws IOException {

		try {
			clientSocket = new Socket(adr.getLocalHost(), portNumber);
			System.out.println("połączono");

			out = new ObjectOutputStream(new BufferedOutputStream(
					clientSocket.getOutputStream()));
			out.flush();

			in = new ObjectInputStream(new BufferedInputStream(
					clientSocket.getInputStream()));

			System.out.println("ok");

		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: localhost.");
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for "
					+ "the connection to: taranis.");
			System.exit(1);
		}

		Thread t = new Thread(this);
		this.isRunning = true;
		t.start();

		/*
		 * BufferedReader stdIn = new BufferedReader( new
		 * InputStreamReader(System.in));
		 */

	}

	@Override
	public void run() {
		DataPacket userInput;
		while (isRunning) {
			try {
				while ((userInput = (DataPacket) in.readObject()) != null) {
					System.out.println(userInput.getTypeOfInformation());
					System.out.println("wyświetlono");
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void close() {
		this.isRunning = false;
		System.out.println("koniec");
		try {
			out.close();
			in.close();
			clientSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
